# 1 导入库及设置GPU
# 1.1 导入库
import torch
import torch.nn as nn
from torchvision import transforms, datasets
import matplotlib.pyplot as plt
from datetime import datetime
import warnings

warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

# 1.2 设置GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 2 数据预处理
# 2.1 数据地址
data_train = '/Users/sunhaoqing/Desktop/pythonProject/深度学习/2 Pytorch入门/data/运动鞋识别/train'
data_test  = '/Users/sunhaoqing/Desktop/pythonProject/深度学习/2 Pytorch入门/data/运动鞋识别/test'

# 2.2 数据标准化
train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean = [0.485, 0.456, 0.406],
        std  = [0.229, 0.224, 0.225]
    )
])

test_transforms = transforms.Compose([
    transforms.Resize([224, 224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean = [0.485, 0.456, 0.406],
        std  = [0.229, 0.224, 0.225]
    )
])

train_dataset = datasets.ImageFolder(data_train, train_transforms)
test_dataset  = datasets.ImageFolder(data_test, test_transforms)

# 2.3 数据加载
batch_size = 32

train_dl = torch.utils.data.DataLoader(
    train_dataset,
    batch_size=batch_size,
    shuffle=True,
    num_workers=0
)

test_dl = torch.utils.data.DataLoader(
    test_dataset,
    batch_size=batch_size,
    shuffle=False,
    num_workers=0
)

# 3 模型构建
classeNames = 2
class Model(nn.Module):
    def __init__(self):
        super(Model,self).__init__()
        self.conv1=nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0),
            nn.BatchNorm2d(12),
            nn.ReLU()
        )

        self.conv2 = nn.Sequential(
            nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0),
            nn.BatchNorm2d(12),
            nn.ReLU()
        )

        self.pool3 = nn.Sequential(
            nn.MaxPool2d(2)
        )

        self.conv4 = nn.Sequential(
            nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, padding=0),
            nn.BatchNorm2d(24),
            nn.ReLU()
        )

        self.conv5 = nn.Sequential(
            nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, padding=0),
            nn.BatchNorm2d(24),
            nn.ReLU()
        )

        self.pool6 = nn.Sequential(
            nn.MaxPool2d(2)
        )

        self.dropout = nn.Sequential(
            nn.Dropout(0.2)
        )

        self.fc = nn.Sequential(
            nn.Linear(in_features=24 * 50 * 50, out_features=classeNames)
        )

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.pool3(x)
        x = self.conv4(x)
        x = self.conv5(x)
        x = self.pool6(x)
        x = self.dropout(x)
        x = torch.flatten(x, start_dim=1)
        x = self.fc(x)

        return x

# 4 训练准备
# 4.1 设置超参数
model = Model().to(device)

loss_fn = nn.CrossEntropyLoss()

learn_rate = 1e-4
lambda1 = lambda epoch: (0.92 ** (epoch // 2))
optimizer = torch.optim.SGD(model.parameters(), lr=learn_rate)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)


# 4.2 训练函数
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)   # 训练集的大小
    num_batches = len(dataloader)    # 批次数目

    train_loss = 0
    train_acc  = 0

    for X, y in dataloader:
        X, y = X.to(device), y.to(device)

        # 计算预测误差
        pred = model(X)
        loss = loss_fn(pred, y)

        # 反向传播
        optimizer.zero_grad()   # grad属性归零
        loss.backward()         # 反向传播
        optimizer.step()        # 每一步自动更新

        # 计算预测误差
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

# 4.3 测试函数
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss, test_acc = 0, 0

    # 当不进行训练时，停止梯度更新，节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            # 计算预测误差
            target_pred = model(imgs)
            loss = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss

# 5 训练
epochs = 40

train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

for epoch in range(epochs):

    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)

    scheduler.step()

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    # 获取当前的学习率
    lr = scheduler.get_last_lr()[0]

    print(f"Epoch:{epoch + 1:2d}, Train_acc:{epoch_train_acc * 100:.1f}%, "
          f"Train_loss:{epoch_train_loss:.3f}, Test_acc:{epoch_test_acc * 100:.1f}%, "
          f"Test_loss:{epoch_test_loss:.3f}, Lr:{lr:.2E}")

# 6 可视化
current_time = datetime.now() # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))

plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.xlabel(current_time)

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.xlabel(current_time)

plt.show()